// Copyright 2008 web2me.dev
//
//   Licensed under the Apache License, Version 2.0 (the "License");
//   you may not use this file except in compliance with the License.
//   You may obtain a copy of the License at
//
//       http://www.apache.org/licenses/LICENSE-2.0
//
//   Unless required by applicable law or agreed to in writing, software
//   distributed under the License is distributed on an "AS IS" BASIS,
//   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//   See the License for the specific language governing permissions and
//   limitations under the License.

package net.web2me.parsers;

import org.apache.log4j.Logger;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import net.web2me.api.AbstractBaseParser;
import net.web2me.api.ParserException;
import net.web2me.api.ProcessFinishedException;
import net.web2me.api.util.DocumentGenerator;
import net.web2me.api.util.Downloader;
import net.web2me.api.util.SiteStreamGenerator;
import net.web2me.api.util.UtilityException;

public class TerraFotologParser extends AbstractBaseParser {
	
	private Logger logger = Logger.getLogger(TerraFotologParser.class);
	private Boolean firstTime = true;
	private String navClass = "";
	private Downloader downloader = new Downloader();

	public void process(String stream) throws ParserException,
			ProcessFinishedException {
		
		/**
		 * <div class="navAnt"><a href="http://fotolog.terra.com.ar/chichisdelmsn:13">ANTERIOR</a></div>
			<div class="navProx"><a href="http://fotolog.terra.com.ar/chichisdelmsn:15">PRÓXIMO</a></div>
		 */
		
		if(firstTime){
			firstTime = false;
			navClass = isFoward() ? "navProx": "navAnt";
		}
		
		Document doc = null;
		
		try {
			doc = DocumentGenerator.generate(stream);
		} catch (Exception e) {
			logger.fatal("Exception caught", e);
			throw new ParserException(e);
		}
		
		saveImage(doc);
		
		logger.debug("Using navClass \"" + navClass + "\"");
		
		NodeList nl = doc.getElementsByTagName("div");
		String nextPicLink = "";
		
		for(int i = 0; i < nl.getLength(); i++){
			Element div = (Element) nl.item(i);
			
			if(div.getAttribute("class").equals("navegacao")){
				NodeList navLinks = div.getElementsByTagName("div");
				Element firstLink = (Element) navLinks.item(0);
				Element secondLink = null;
				
				logger.debug("\"Navegacao\" links " + navLinks.getLength());
				
				if(navLinks.getLength() > 1){
					secondLink = (Element) navLinks.item(1);
				}
				
				if(firstLink.getAttribute("class").equals(navClass)){
					logger.debug("Using firstLink");
					nextPicLink = ((Element) firstLink.getElementsByTagName("a").item(0)).getAttribute("href");
					break;
				}else{
					if(secondLink != null){
						if(secondLink.getAttribute("class").equals(navClass)){
							logger.debug("Using secondLink");
							nextPicLink = ((Element) secondLink.getElementsByTagName("a").item(0)).getAttribute("href");
							break;
						}
					}else{
						//Process finished
						throw new ProcessFinishedException();
					}
				}
			}
		}
		
		if(nextPicLink.equals("")){
			throw new ProcessFinishedException();
		}
		
		String newStream = "";
		
		try {
			newStream = SiteStreamGenerator.getStream(nextPicLink);
		} catch (UtilityException e) {
			logger.fatal("UtilityException caught", e);
			throw new ParserException(e);
		}
		
		process(newStream);
	}
	
	private void saveImage(Document doc) throws ParserException{
		NodeList divs = doc.getElementsByTagName("div");
		Element photoDiv = null; 
		
		for(int i = 0; i < divs.getLength(); i++){
			Element div = (Element) divs.item(i);
			
			if(div.getAttribute("id").equals("foto")){
				photoDiv = div;
			}
		}
		
		Element photo = (Element) (photoDiv.getElementsByTagName("img")).item(0);
		String picUrl = photo.getAttribute("src");
		
		String finalDir = getDir() + "/" + getUserName();
		
		try {
			downloader.setUrl(picUrl);
			downloader.setDestinyDirectory(finalDir);
			downloader.download();
		} catch (UtilityException e) {
			logger.fatal("UtilityException caught", e);
			throw new ParserException(e);
		}
		
	}

	private String getUserName() {
		//From http://fotolog.terra.com.ar/chichisdelmsn:13 
		//To chichisdelmsn
		
		String name = getUrl().replaceAll(":\\d", "");
		name = name.replaceAll("http://fotolog.terra.com.ar/", "");
		name = name.replaceAll("http://fotolog.terra.cl/", "");
		
		logger.debug("Returning user name \"" + name + "\"");
		
		return name;
	}
	
	private Boolean isFoward(){
		int iof = getUrl().indexOf(":") + 1;
		return getUrl().indexOf(":", iof) > - 1;
	}

}
